﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using BathhouseService.CURD.ViewModels.RechargeRecordVMs;
using BathhouseService.Models.SqlModels;
using System.Linq;
using BathhouseService.Models.FrameEnumeration;
using BathhouseService.Models.Commonality;

namespace BathhouseService.Controllers
{
    [Area("CURD")]
    [ActionDescription("套餐办理")]
    public partial class RechargeRecordController : BaseController
    {
        #region 搜索
        [ActionDescription("搜索")]
        public ActionResult Index()
        {
            var vm = CreateVM<RechargeRecordListVM>();
            return PartialView(vm);
        }

        [ActionDescription("搜索")]
        [HttpPost]
        public string Search(RechargeRecordListVM vm)
        {
            return vm.GetJson(false);
        }

        #endregion

        #region 新建
        [ActionDescription("发卡")]
        public ActionResult Create()
        {
            var vm = CreateVM<RechargeRecordVM>();
            return PartialView(vm);
        }
        [HttpPost]
        [ActionDescription("发卡")]
        public ActionResult Create(RechargeRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                var count = DC.Set<RechargeRecord>().Count();
                vm.Entity.OrderId = AutomaticNumbering.GetNumber(count, "TC.");
                vm.Entity.PaymentTime = DateTime.Now;
                vm.Entity.CustomerName = DC.Set<FrameworkUserBase>().FirstOrDefault(x => x.ID == vm.Entity.CustomerId).Name;
                vm.Entity.ServicePersonId = LoginUserInfo.Id;
                vm.Entity.ServicePersonName = LoginUserInfo.Name;
                vm.Entity.IsValid = true;
                vm.Entity.CreateBy = LoginUserInfo.Name;
                vm.Entity.CreateTime = DateTime.Now;
                vm.Entity.HandlTypeEnums = HandlTypeEnum.发卡;
                DC.Set<RechargeRecord>().Add(vm.Entity);
                //选择项目包含服务
                var packageService = DC.Set<PackageServiceSettings>()
                    .Where(x => x.PackageServiceId == vm.Entity.PackageServiceId).ToList();
                //用户已拥有服务
                foreach (var item in packageService)
                {
                    //查询用户是否已购买此服务
                    var thisAcquired = DC.Set<ServiceAcquired>()
                        .FirstOrDefault(x => x.FrameworkUserBaseId == vm.Entity.CustomerId && x.ValueAddedServicesId == item.ValueAddedServicesId);
                    if (thisAcquired != null)
                    {
                        thisAcquired.RemainingTimes += item.Count;
                        thisAcquired.UpdateTime = DateTime.Now;
                        thisAcquired.UpdateBy = LoginUserInfo.Name;
                        thisAcquired.LastService = vm.Entity.PackageServiceId;
                        thisAcquired.IsValid = true;
                        DC.Set<ServiceAcquired>().Update(thisAcquired);
                    }
                    else
                    {
                        ServiceAcquired acquired = new ServiceAcquired
                        {
                            ValueAddedServicesId = item.ValueAddedServicesId,
                            FrameworkUserBaseId = vm.Entity.CustomerId,
                            RemainingTimes = item.Count,
                            CreateTime = DateTime.Now,
                            CreateBy = LoginUserInfo.Name,
                            IsValid = true
                        };
                        DC.Set<ServiceAcquired>().Add(acquired);
                    }
                }
                DC.SaveChanges();
                if (!ModelState.IsValid)
                {
                    vm.DoReInit();
                    return PartialView(vm);
                }
                else
                {
                    return FFResult().CloseDialog().RefreshGrid();
                }
            }
        }

        
        #endregion

        #region 修改
        [ActionDescription("退卡")]
        public ActionResult Edit(string id)
        {
            var vm = CreateVM<RechargeRecordVM>(id);
            return PartialView(vm);
        }

        [ActionDescription("退卡")]
        [HttpPost]
        [ValidateFormItemOnly]
        public ActionResult Edit(RechargeRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                var model = DC.Set<RechargeRecord>().FirstOrDefault(x => x.ID == vm.Entity.ID);
                model.HandlTypeEnums = HandlTypeEnum.退卡;        
                DC.Set<RechargeRecord>().Update(model);
                var packageService = DC.Set<PackageServiceSettings>()
                    .Where(x => x.PackageServiceId == vm.Entity.PackageServiceId).ToList();
                //用户已拥有服务
                foreach (var item in packageService)
                {
                    //查询用户是否已购买此服务
                    var thisAcquired = DC.Set<ServiceAcquired>()
                        .FirstOrDefault(x => x.FrameworkUserBaseId == model.CustomerId && x.ValueAddedServicesId == item.ValueAddedServicesId);
                    if (thisAcquired != null)
                    {
                        thisAcquired.RemainingTimes -= item.Count;
                        thisAcquired.UpdateTime = DateTime.Now;
                        thisAcquired.UpdateBy = LoginUserInfo.Name;
                        thisAcquired.IsValid = true;
                        thisAcquired.LastService = model.PackageServiceId;
                        DC.Set<ServiceAcquired>().Update(thisAcquired);
                    }
                    else
                    {
                        ServiceAcquired acquired = new ServiceAcquired
                        {
                            ValueAddedServicesId = item.ValueAddedServicesId,
                            FrameworkUserBaseId = model.CustomerId,
                            RemainingTimes = item.Count,
                            CreateTime = DateTime.Now,
                            CreateBy = LoginUserInfo.Name,
                            IsValid = true
                        };
                        DC.Set<ServiceAcquired>().Add(acquired);
                    }
                }
                DC.SaveChanges();
                if (!ModelState.IsValid)
                {
                    vm.DoReInit();
                    return PartialView(vm);
                }
                else
                {
                    return FFResult().CloseDialog().RefreshGridRow(vm.Entity.ID);
                }
            }
        }
        #endregion

        #region 删除
        [ActionDescription("删除")]
        public ActionResult Delete(string id)
        {
            var vm = CreateVM<RechargeRecordVM>(id);
            return PartialView(vm);
        }

        [ActionDescription("删除")]
        [HttpPost]
        public ActionResult Delete(RechargeRecordVM vm)
        {
            var model = DC.Set<RechargeRecord>().FirstOrDefault(x => x.ID == vm.Entity.ID);
            model.ActualPayment = vm.Entity.ActualPayment;
            DC.Set<RechargeRecord>().Update(model);
            DC.SaveChanges();

            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid();
            }
        }
        #endregion

        #region 详细
        [ActionDescription("详细")]
        public ActionResult Details(string id)
        {
            var vm = CreateVM<RechargeRecordVM>(id);
            return PartialView(vm);
        }
        #endregion

        #region 批量修改
        [HttpPost]
        [ActionDescription("批量修改")]
        public ActionResult BatchEdit(string[] IDs)
        {
            var vm = CreateVM<RechargeRecordBatchVM>(Ids: IDs);
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("批量修改")]
        public ActionResult DoBatchEdit(RechargeRecordBatchVM vm, IFormCollection nouse)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return PartialView("BatchEdit", vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert("操作成功，共有" + vm.Ids.Length + "条数据被修改");
            }
        }
        #endregion

        #region 批量删除
        [HttpPost]
        [ActionDescription("批量删除")]
        public ActionResult BatchDelete(string[] IDs)
        {
            var vm = CreateVM<RechargeRecordBatchVM>(Ids: IDs);
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("批量删除")]
        public ActionResult DoBatchDelete(RechargeRecordBatchVM vm, IFormCollection nouse)
        {
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return PartialView("BatchDelete", vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert("操作成功，共有" + vm.Ids.Length + "条数据被删除");
            }
        }
        #endregion

        #region 导入
        [ActionDescription("导入")]
        public ActionResult Import()
        {
            var vm = CreateVM<RechargeRecordImportVM>();
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("导入")]
        public ActionResult Import(RechargeRecordImportVM vm, IFormCollection nouse)
        {
            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return PartialView(vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert("成功导入 " + vm.EntityList.Count.ToString() + " 行数据");
            }
        }
        #endregion

        [ActionDescription("导出")]
        [HttpPost]
        public IActionResult ExportExcel(RechargeRecordListVM vm)
        {
            vm.SearcherMode = vm.Ids != null && vm.Ids.Count > 0 ? ListVMSearchModeEnum.CheckExport : ListVMSearchModeEnum.Export;
            var data = vm.GenerateExcel();
            return File(data, "application/vnd.ms-excel", $"Export_RechargeRecord_{DateTime.Now.ToString("yyyy-MM-dd")}.xls");
        }

    }
}
